import { _decorator, Component, Label, Node, EventHandler, tween, Vec2, Vec3, UITransform, Sprite, Color, Tween, view, find } from 'cc';
import { EconomicCom } from '../../Entity/Component/EconomicCom';
import { Unit } from '../../Entity/Unit';
import GameEventMgr, { GameEvent } from '../../Model/GameEventMgr';
import { Global } from '../../Util/Global';
import SoundCtrl from '../../Ctrl/SoundCtrl';
import { UICtrl } from '../../Ctrl/UICtrl';
import { EconIconUI } from './EconIconUI';
const { ccclass, property } = _decorator;

@ccclass('EconomicViewUI')
export class EconomicViewUI extends Component {

    @property(EconIconUI)
    public econIconUI: EconIconUI = null;

    @property({ type: Label, displayName: "电力文本" })
    public econ_elec: Label = null;
    @property({ type: Label, displayName: "资源文本" })
    public econ_mine: Label = null;
    @property({ type: Label, displayName: "难度等级" })
    public difficulty: Label = null;
    @property({ type: Label, displayName: "星球等级" })
    public level: Label = null;
    @property({ type: Node, displayName: "升级提示" })
    public upTip: Node = null;
    // @property({ type: Sprite, displayName: "用电" })
    // public powerUsing: Sprite = null;
    @property({ type: Node, displayName: "过载提示" })
    public powerTip: Node = null;
    @property({ type: Node, displayName: "资源提示" })
    public mineTip: Node = null;

    public target_economic: EconomicCom = null;

    private interval = 3;

    // private badPowerColor: Color = new Color("#FF0000");
    // private powerIcon: Sprite = null;
    start() {

        GameEventMgr.Register(this, GameEvent.ECViewDataChangeToTip, this.onDataChangeEventHandle.bind(this))
        // GameEventMgr.Register(this, GameEvent.UnitLevelUp, this.onPlayerLevelUpEventHandle.bind(this))
        GameEventMgr.Register(this, GameEvent.PlayerDataChange, this.onPlayerLevelUpEventHandle.bind(this));
        GameEventMgr.Register(this, GameEvent.GameReset, this.onGameResetEventHandle.bind(this))
        GameEventMgr.Register(this, GameEvent.GameStart, this.onGameResetEventHandle.bind(this))
        GameEventMgr.Register(this, GameEvent.FactoryConstructionFailed, this.onFactoryConstructionFailedHandle.bind(this))

        this.difficulty.string = 'lv' + Global.gameManager.playerData.difficulty;
        let lv = Global.gameManager.playerData.level
        this.level.string = 'lv' + lv;

        // this.powerIcon = this.powerUsing.node.getChildByName('dianli_icon').getComponent(Sprite);

        //"resizable": true
        console.log('屏幕宽与设计宽缩放比', Global.screenAdjustScale);
        if (Global.screenAdjustScale.width < 1) {
            this.node.setPosition(0, 0);
        }
    }

    private _elec_sum = 0;
    private _mine_sum = 0;

    private _sum_time = 0;
    update(deltaTime: number) {
        this._tipGameMsgInterval -= deltaTime;
        this._tipGameMsgInterval = this._tipGameMsgInterval < 0 ? 0 : this._tipGameMsgInterval;

        this._sum_time += deltaTime;
        if (this._sum_time > 0.2) {
            this._sum_time = 0;
            if (this._elec_sum != 0) {
                let _num = this._elec_sum;
                let msg = _num > 0 ? '+' + _num.toFixed(0) : _num.toFixed(0) + '';
                this.createDataChangeTip(this.econ_elec, msg, _num > 0 ? 1 : -1);
            }

            if (this._mine_sum != 0) {
                let _num = this._mine_sum;
                let msg = _num > 0 ? '+' + _num.toFixed(0) : _num.toFixed(0) + '';
                this.createDataChangeTip(this.econ_mine, msg, _num > 0 ? 1 : -1);
            }
            this._elec_sum = 0;
            this._mine_sum = 0;
        }


        if (!this.target_economic) {
            return;
        }

        this.econIconUI.econCom = this.target_economic;
        this.econIconUI.RefreshPowerContent();
        this.econIconUI.RefreshMetalContent();
        this.econIconUI.RefreshShieldContent();
        // this.econ_elec.string = this.target_economic.electric_power_remain.toFixed(1);
        // this.econ_mine.string = this.target_economic.mine_res.toFixed(1);

        // this.powerUsing.fillRange = this.target_economic.power_load;
        // if (this.powerUsing.fillRange > 0.8) {
        //     this.powerIcon.color = this.badPowerColor;
        // }
        // else {
        //     this.powerIcon.color = Color.WHITE;
        // }

        this.interval = this.interval - deltaTime;
        if (this.interval < 0) {
            this.interval = 3;

            let nextLvCfg = Global.config['levelCfg'][Global.gameManager.playerData.level];
            if (nextLvCfg && this.target_economic.mine_res > nextLvCfg.levelUpCost) {
                //可升级
                this.upTip.active = true;
                find('level/btn_add', this.node).active = true;
            }
            else {
                this.upTip.active = false;
                find('level/btn_add', this.node).active = false;
            }
        }
    }

    onClickUpLevel(event: EventHandler, customEventData: string) {
        if (Global.gameManager.gameover) {
            return;
        }
        let playerData = Global.gameManager.playerData;
        let lv = playerData.level;
        if (lv >= Global.config['levelCfg'].length) {
            return;
        }
        let cost = Global.config['levelCfg'][lv].levelUpCost;

        this.upTip.active = false;

        if (this.target_economic.mine_res - cost > 0) {
            this.target_economic.CostRes(cost);
            GameEventMgr.Dispatch(GameEvent.ECViewDataChangeToTip, 'mine', -cost);
        }
        else {
            SoundCtrl.playEffect('mouserelease1');
            return;
        }
        playerData.level = playerData.level + 1;
        Global.gameManager.playerUnit.levelUpCom.level = playerData.level;
        // GameEventMgr.Dispatch(GameEvent.UnitLevelUp, this.target_economic.getComponent(Unit));
        GameEventMgr.Dispatch(GameEvent.PlayerDataChange);
    }

    onGameResetEventHandle() {

        this.difficulty.string = 'lv' + Global.gameManager.playerData.difficulty;
        let lv = Global.gameManager.playerData.level
        this.level.string = 'lv' + lv;
    }

    private _tipGameMsgInterval = 1;
    onDataChangeEventHandle(type: string, num: number) {
        if (type == 'elec') {
            this._elec_sum += num;
            if (num < 0 && this._tipGameMsgInterval == 0) {
                this._tipGameMsgInterval = 3;
                GameEventMgr.Dispatch(GameEvent.TipGameMessage, 'MOSS：警告！遭受未知打击！电力供应受损！！！');
            }
        }
        else if (type == 'mine') {
            this._mine_sum += num;
        }
        else {
            return;
        }
    }

    onPlayerLevelUpEventHandle() {
        if (this.target_economic.getComponent(Unit).playerCtrl) {

            let lv = 'lv' + Global.gameManager.playerData.level;
            if (lv != this.level.string) {
                this.level.string = lv;
                this.createDataChangeTip(this.level, '+1', 1);
            }

            let df = 'lv' + Global.gameManager.playerData.difficulty;
            if (df != this.difficulty.string) {
                this.difficulty.string = df;
                this.createDataChangeTip(this.difficulty, '+1', 1);
            }
        }
    }

    createDataChangeTip(parentTxt: Label, msg: string, yRadio = -1) {
        let tipNode = new Node();
        let label = tipNode.addComponent(Label);
        let tran = tipNode.addComponent(UITransform);
        // tran.setAnchorPoint(0, 0.5);
        label.fontSize = parentTxt.fontSize;
        label.string = msg;
        tipNode.parent = parentTxt.node;
        tipNode.layer = UICtrl.UILayer;

        tween(tipNode)
            .set({ position: new Vec3(0, yRadio * 20, 0) })
            .to(1, { position: new Vec3(0, yRadio * 50, 0) })
            .call(() => { tipNode.destroy() })
            .start();
    }

    onFactoryConstructionFailedHandle(reason: string) {

        let tip = this.mineTip;
        if (reason == 'no_elec') {
            tip = this.powerTip;
        }
        else if (reason == 'no_mine') {
            tip = this.mineTip;
        }
        else {
            return;
        }

        tip.active = true;
        Tween.stopAllByTarget(tip);
        tween(tip).delay(3).call(() => {
            tip.active = false;
        }).start();
    }
}


